package com.carpedil.boot.controller;

import com.carpedil.boot.entity.User;
import com.carpedil.boot.entity.dto.UserDTO;
import com.carpedil.boot.service.UserService;
import com.carpedil.dto.ScoreDto;
import com.carpedil.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/** @author Administrator */
@RestController
@RequestMapping("/user")
public class UserController {
  @Autowired UserService userService;

  @PostMapping("/register")
  public ModelAndView register(
      User user, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
    // 获取文件名
    String filename = file.getOriginalFilename();
    // 截取文件后缀
    String suffix = "";
    if (filename != null) {
      suffix = filename.substring(filename.lastIndexOf("."));
    }
    // 生成uuid
    UUID uuid = UUID.randomUUID();
    String newFilePathName = "/upload/" + uuid + suffix;

    try {
      file.transferTo(new File("f:" + newFilePathName));
      user.setAvatar("http://127.0.0.1:8080" + newFilePathName);
      user.setRegistrationTime(LocalDateTime.now());
    } catch (IOException e) {
      e.printStackTrace();
    }
    userService.registerUser(user);
    return new ModelAndView("redirect:/index.html");
  }

  @GetMapping("/list")
  public List<User> getAllUsers() {
    return userService.getUsers();
  }

  @PostMapping("/info")
  public UserDto findUser(@RequestBody UserDto userDto) {
    return userService.getUserByUserNameAndPassword(userDto.getUsername(), userDto.getPassword());
  }

  @GetMapping("/login/{username}/{password}")
  public List<ScoreDto> login(
      @PathVariable("username") String username, @PathVariable("password") String password) {
    return userService.login(username, password);
  }

  @GetMapping("/trip/{username}")
  public UserDTO getUserTravelInfo(@PathVariable("username") String username) {
    return userService.getUserTravelInfo(username);
  }
}
